package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.constant.bean.EmpPointPojo;
import com.stylefeng.guns.common.constant.bean.PointTypePojo;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDeptService;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmpPointsService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import com.stylefeng.guns.modular.train.transfer.EmpPointsDto;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 员工积分控制器
 *
 * @author fengshuonan
 * @Date 2018-01-31 16:48:50
 */
@Controller
@RequestMapping("/empPoints")
public class EmpPointsController extends BaseController {

    private String PREFIX = "/train/empPoints/";
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IEmpPointsService empPointsService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;

    /**
     * 跳转到员工积分首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "empPoints.html";
    }

    /**
     * 跳转到添加员工积分
     */
    @RequestMapping("/empPoints_add")
    public String empPointsAdd() {
        return PREFIX + "empPoints_add.html";
    }

    /**
     * 跳转到修改员工积分
     */
    @RequestMapping("/empPoints_update/{empPointsId}")
    public String empPointsUpdate(@PathVariable Integer empPointsId, Model model) {
        EmpPoints empPoints = empPointsService.selectById(empPointsId);
        model.addAttribute("item",empPoints);
        LogObjectHolder.me().set(empPoints);
        return PREFIX + "empPoints_edit.html";
    }

    /**
     * 获取员工积分列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, String year, Double max, Double min) {

        return getEmpPoints(employee, year, max, min);
    }

    public List<EmpPointsDto> getEmpPoints(Employee employee, String year, Double max, Double min) {
        List<Employee> employees2 = employeeService.selectList(null);
        Map<String,Employee> employeeMap = new HashMap<>();
        employees2.forEach(e -> employeeMap.put(e.getEmpCode(),e));

//        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null && year == null){
//
//            List<EmpPointsDto> empPointsDtos = fullEmpInfo(employeeMap, empPointsService.selectList(null));
//            return empPointsDtos;
//        }


        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        List<EmpPoints> empPointss;
        if(employees == null || employees.size() < 1){
            empPointss = empPointsService.selectList(null);
        }else {
            Set<String> empCodes = new HashSet<>();
            employees.forEach(e -> {
                empCodes.add(e.getEmpCode());
            });
            EntityWrapper<EmpPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(!StringUtils.isEmpty(year)){
                nwWrapper.eq("year",year);
            }

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 99999.0 : max;
                nwWrapper.between("total_point",min,max);
            }

            empPointss = empPointsService.selectList(nwWrapper);
        }

        List<EmpPointsDto> empPointsDtos = fullEmpInfo(employeeMap, empPointss);
        return empPointsDtos;
    }

    public List<EmpPointsDto> fullEmpInfo(Map<String, Employee> employeeMap, List<EmpPoints> empPointss) {
        List<EmpPointsDto> empPointsDtos = getEmpPointsDtos(empPointss);

        QualityGradeRule qualityGradeRule = new QualityGradeRule();
        qualityGradeRule.setGradeType(Const.TRAIN_START);
        EntityWrapper<QualityGradeRule> wrapper = new EntityWrapper<>();
        wrapper.setEntity(qualityGradeRule);
        wrapper.orderBy("integral");
        List<QualityGradeRule> qualityGradeRules = qualityGradeRuleService.selectList(wrapper);

        empPointsDtos.forEach(empPointsDto -> {
            String empCode = empPointsDto.getEmpCode();
            Employee employee1 = employeeMap.get(empCode);

            empPointsDto.setLaborType(employee1.getLaborType());
            empPointsDto.setErpCode(employee1.getErpCode());
            empPointsDto.setPlaceName(employee1.getPlaceName());
            empPointsDto.setDeptName(employee1.getDeptName());
            empPointsDto.setTeamName(employee1.getTeamName());
            empPointsDto.setPost(employee1.getPost());
            empPointsDto.setPostType(employee1.getPostType());



            //设置积分星级
            String star  = "一星";
            double totalPoint = empPointsDto.getTotalPoint();
            if(totalPoint < qualityGradeRules.get(0).getIntegral()){
                star  = "一星";
            }else if(totalPoint < qualityGradeRules.get(1).getIntegral()){
                star  = "二星";
            }else if(totalPoint < qualityGradeRules.get(2).getIntegral()){
                star  = "三星";
            }else if(totalPoint < qualityGradeRules.get(3).getIntegral()){
                star  = "四星";
            }else{
                star  = "五星";
            }
            empPointsDto.setStart(star);

        });
        convertToString(empPointsDtos);
        return empPointsDtos;
    }

    private void convertToString(List<EmpPointsDto> employees){
        List<Dict> byPName = dictService.getByPName(Const.POST_TYPE);
        Map<String,String> postTypeMap = new HashMap<>();

        for (Dict dict : byPName) {
            postTypeMap.put(dict.getNum().toString(), dict.getName().toString());
        }

        for (EmpPointsDto employee : employees) {
            String name = postTypeMap.get(employee.getPostType());
            employee.setPostType(name);
        }
    }

    public List<EmpPointsDto> getEmpPointsDtos(List<EmpPoints> empPointss) {
        List<EmpPointsDto> empPointsDtos = new ArrayList<>();
        for (EmpPoints empPoints : empPointss) {

            EmpPointsDto empPointsDto = JSONObject.parseObject(empPoints.getModularPonit(), EmpPointsDto.class);

            empPointsDto.setId(empPoints.getId());
            empPointsDto.setYear(empPoints.getYear());
            empPointsDto.setEmpCode(empPoints.getEmpCode());
            empPointsDto.setEmpName(empPoints.getEmpName());
            empPointsDto.setTotalPoint(empPoints.getTotalPoint());
            empPointsDtos.add(empPointsDto);
        }
        return empPointsDtos;
    }

    /**
     * 导出员工积分
     */
    @RequestMapping(value = "/exportTrainPoint")
    @ResponseBody
    public void exportTrainPoint(Employee employee, String year, Double max, Double min, HttpServletResponse response ) {
        MvcResult mvcResult = new MvcResult();

        List<EmpPointsDto> empPoints = getEmpPoints(employee, year, max, min);
        Map<String,Object> data = new HashMap<>();
        data.put("points",empPoints);

        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        String tempPath = jarFile.getParent()+"/temp/";
        String excelPath = jarFile.getParent()+"/template/";
        try {
            TemplateExportParams params = new TemplateExportParams(
                    excelPath + "员工总积分模板.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, data);

//            File savefile = new File(tempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filename = "EmployeeTrainFiles.xlsx";
//            String filePathName = tempPath + filename;

            String fileName = "员工总积分统计表.xlsx";
//            String filePathName  = tempPath + filename;

            OutputStream outputStream=response.getOutputStream();
//            String fileName="员工基本信息统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();

        }catch (Exception e){
            e.getStackTrace();
        }
    }



    /**
     * 新增员工积分
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(EmpPoints empPoints) {
        empPointsService.insert(empPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除员工积分
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String empPointsId) {
        empPointsService.deleteById(empPointsId);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/g_search")
    public String gSearch(Model model) {
        List<Dept> depts = deptService.getFirstLevelDept();
        List<Dict> posts = dictService.getByPName(Const.POST_TYPE);
        model.addAttribute("depts",depts);
        model.addAttribute("posts",posts);
        return PREFIX + "g_search.html";
    }

    /**
     * 修改员工积分
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(EmpPoints empPoints) {
        empPointsService.updateById(empPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * 员工积分详情
     */
    @RequestMapping(value = "/detail/{empPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("empPointsId") Integer empPointsId) {
        return empPointsService.selectById(empPointsId);
    }


    /**
     * 跳转到导入员工积分
     */
    @RequestMapping("/empPoints_import")
    public String empPointsImport() {
        return PREFIX + "empPoints_import.html";
    }

    /**
     * 导入员工积分
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        try {
            List<EmpPoints> empPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), EmpPoints.class, params);
            Date now = new Date();
            empPointss.forEach(empPoints -> {
                /*empPoints.set(Const.IMPORT_TYPE_XML);
                empPoints.setCreateDate(now);*/
            });
            empPointsService.insertBatch(empPointss);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.SUCCESS_TIP;
    }

    /**
     * 导出员工积分
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request,HttpServletResponse response) throws IOException {
        List<String> empCodes=null;
        String year="";
        List<EmpPointPojo> empPointPojos=empPointsService.selectEmpByYearInCode(year,empCodes);
        empPointPojos.forEach(item->{
            item.updatePointType(JSON.parseObject(item.getModularPonit(), PointTypePojo.class));
        });
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode("培训管理积分总表","UTF-8")+".xls");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), EmpPointPojo.class, empPointPojos);
        workbook.write(response.getOutputStream());
    }
}
